package com.opencee.cloud.uaa.provider.service;

import com.opencee.cloud.base.api.IBaseApplicationApi;
import com.opencee.cloud.base.vo.BaseApplicationDetailsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.stereotype.Service;

/**
 * @author yadu
 */
@Service
public class AppClientDetailsService implements ClientDetailsService {

    @Autowired
    private IBaseApplicationApi appClient;

    /**
     * Load a client by the client id. This method must not return null.
     *
     * @param clientId The client id.
     * @return The client details (never null).
     * @throws ClientRegistrationException If the client account is locked, expired, disabled, or invalid for any other reason.
     */
    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        BaseApplicationDetailsVO app = appClient.getByAppKey(clientId).getData();
        if (app == null) {
            throw new NoSuchClientException("无效的客户端: " + clientId);
        }
        if (app.getStatus() != 1) {
            throw new ClientRegistrationException("客户端暂不可用");
        }
        return app.getClient();
    }
}
